from django.contrib.auth import login
from django.db import DatabaseError
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views import View
import re
from django import http
from apps.users.models import User
from utils.response_code import RETCODE
# Create your views here.


########用户名重复注册############
class UersnameCountView(View):
    def get(self,request,username):
        count = User.objects.filter(username=username).count()
        return http.JsonResponse({"code":RETCODE.OK,"errmsg":"OK","count":count})

########手机号重复注册############
class MobileCountView(View):
    def get(self,request,mobile):
        count = User.objects.filter(mobile=mobile).count()
        return http.JsonResponse({"code":RETCODE.OK,"errmsg":"OK","count":count})

#######用户注册##############
class RegisterView(View):

    def get(self,request):
        '''提供用户注册'''
        return render(request,"register.html")

    def post(self,request):
        '''实现用户注册逻辑'''
        # 1. 接收参数: 前端发送参数的方式决定了后端读取的方式  post 表单参数
        username = request.POST.get("username")
        password = request.POST.get("password")
        password2 = request.POST.get("password2")
        mobile = request.POST.get("mobile")
        allow = request.POST.get("allow")
        # 2. 校验参数: 前后端校验逻辑要分开, 且逻辑要一致,后端校验逻辑大于等于前端校验逻辑
        # 判断参数是否齐全
        # all() 用来判断一些数据是否为空,将要判断的数据放在列表中作为参数.
        # 若任意一个数据为空,就返回False,全部都不为空就返回True
        if not all([username,password,password2,mobile,allow]):
            return http.HttpResponseForbidden("缺少必传参数")
        # 判断用户名是否是5-20个字符
        if not re.match(r"^[a-zA-Z0-9_-]{5,20}$", username):
            return http.HttpResponseForbidden("参数username错误")
        # 判断密码是否是8-20个数字
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return http.HttpResponseForbidden('请输入8-20位的密码')
        # 判断两次密码是否一致
        if password != password2:
            return http.HttpResponseForbidden('两次输入的密码不一致')
        # 判断手机号是否合法
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseForbidden('请输入正确的手机号码')
        # 判断是否勾选用户协议
        if allow != 'on':
            return http.HttpResponseForbidden('请勾选用户协议')

        # Django的用户认证系统提供的注册方法,set_password对密码进行加密所以选这个
        try:
           user = User.objects.create_user(username=username,
                                 password=password,
                                 mobile=mobile)
        except DatabaseError:
            return render(request,"register.html",{'register_errmsg':"注册失败"})
        # 4. 状态保持:注册成功即登陆成功,登陆的本质就是做状态保持
        # login() 默认将状态保持信息写入到浏览器和服务端的数据库(redis:1)
        login(request,user)

        # 5. 响应结果: 注册成功重定向到首页
        # return http.HttpResponse("注册成功")
        # return redirect(reverse("子应用总路由命名空间:子路由命名空间"))
        return redirect(reverse("contents:index"))

